package com.ps.service.person.imp;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.ps.dao.BaseDaoSupport;
import com.ps.dao.person.EmployeeDAO;
import com.ps.dao.setting.AreaDAO;
import com.ps.dao.setting.RoleDAO;
import com.ps.entity.Result;
import com.ps.entity.Status;
import com.ps.entity.person.Manager;
import com.ps.global.Globals;
import com.ps.pojo.person.Employee;
import com.ps.pojo.setting.Area;
import com.ps.pojo.setting.FunctionModule;
import com.ps.pojo.setting.Role;

import com.ps.service.BaseService;
import com.ps.service.BaseServiceSupport;
import com.ps.service.person.EmployeeService;
import com.ps.service.setting.UnqueNumberService;
import com.ps.util.Kit;
import com.ps.util.PaginationSupport;
import com.ps.util.R;
import com.sun.org.apache.commons.beanutils.BeanUtils;

public class EmployeeServiceImp extends BaseServiceSupport<Employee> implements EmployeeService {

	@Autowired
	private EmployeeDAO employeeDAO;
	
	@Autowired
	private RoleDAO roleDAO;
	
	@Autowired
	private AreaDAO areaDAO;
	
	@Autowired
	private UnqueNumberService unqueNumberService;
	

	
	@SuppressWarnings("unchecked")
	public Employee login(String username, String pwd) {
		Employee emp = null;
		try {
			List list =  employeeDAO.findByUserName(username);
			if (list != null && list.size() == 1)  {
				emp = (Employee)list.get(0);
				if (StringUtils.equals(emp.getPassword(), pwd)) {
					return emp;
				} else {
					return null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return emp;
	}

	/**
	 * 查找管理员信息
	 * @param pageSize
	 * @param startIndex
	 * @return
	 */
    @SuppressWarnings("unchecked")
	public Result findManagerByPage(final int pageSize,final int startIndex){
    	DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Employee.class);
    	detachedCriteria.add(Restrictions.ne(EmployeeDAO.ROLE_ID, Globals.NORMAL_ROLE_ID));
    	detachedCriteria.add(Restrictions.ne(EmployeeDAO.JURISDICTIONS, 0));

    	Order order = Order.desc("employeeId");
        Result result = this.findPageByCriteria(detachedCriteria, pageSize, startIndex, order);
        try {
            if (StringUtils.equals(result.getStatus().getCode(), Status.SUCCES)) {
            	PaginationSupport<Employee> paginationSupport = (PaginationSupport<Employee> )result.getDatas();
            	List<Employee> empList = paginationSupport.getItems();
            	List<Manager> managerList = new ArrayList<Manager>();
                
            	for (Employee emp : empList) {
            		Manager manager = new Manager();
            		emp.setPassword(null);
            		BeanUtils.copyProperties(manager, emp);
            		if (emp.getRoleId().intValue() == Globals.ADMIN_ROLE_ID) {
            			manager.setRoleName(R.string.getProperty("admin_role_name"));
            			manager.setAreaName(R.string.getProperty("full_area"));
            		} else {
            			Role role = roleDAO.findById(emp.getRoleId());
            			Area area = areaDAO.findById(emp.getJurisdictions());
            			if (role != null) manager.setRoleName(role.getName());
            			if (area != null) manager.setAreaName(area.getName());
            		}
            		managerList.add(manager);
            	}
            	PaginationSupport<Manager> pagination = 
            		new PaginationSupport(managerList, paginationSupport.getTotalCount(), paginationSupport.getPageSize(), paginationSupport.getStartIndex());
            	result.setDatas(pagination);
            }
        } catch (Exception e) {
        	log.error("findManagerByPage exception ", e);
        }

        
    	return result;
    }
    
    

    
    /**
     * 添加管理员
     * @param manager
     * @return
     */
    public Result addManager(Manager manager, String password) {
    	Employee employee = new Employee();
    	Result result = Kit.createResult();
    	try {
    		int count = this.getCountByProperty(EmployeeDAO.USER_NAME, manager.getUserName());
    		
    		if (count > 0) {
    			result.getStatus().setCode(Status.FAIL);
    			result.getStatus().setMessage(R.string.getProperty("user_name_used"));
    		}  else {
        		BeanUtils.copyProperties(employee, manager);
        		String employeeNum = unqueNumberService.increaseCodeValue(Globals.NAME_CODE_EMP_NO);
        		employee.setEmployeeNum(employeeNum);
        		employee.setPassword(password);
        		employeeDAO.save(employee);
                result.getStatus().setMessage(R.string.getProperty("addsucces"));
                result.setDatas(employee.getEmployeeId());
    		}
    		
    		

		} catch (Exception e) {
			log.error("addRole exception ", e);
			result.getStatus().setCode(Status.FAIL);
			result.getStatus().setMessage(R.string.getProperty("addfail"));
		}
		
		return result;
    }
    
    
	public Result updateManager(Manager manager, String password) {
		Result result = Kit.createResult();
		try {
			Employee employee = employeeDAO.findById(manager.getEmployeeId());
			BeanUtils.copyProperties(employee, manager);
			employee.setPassword(password);
			employeeDAO.update(employee);
            result.getStatus().setMessage(R.string.getProperty("updsucces"));
            result.setDatas(employee.getEmployeeId());
		} catch (Exception e) {
			log.error("updateManager exception ", e);
			result.getStatus().setCode(Status.FAIL);
			result.getStatus().setMessage(R.string.getProperty("updfail"));
		}
		return result;
	}   
    
    
	@Override
	public BaseDaoSupport<Employee> getBaseDao() {
		// TODO Auto-generated method stub
		return employeeDAO;
	}





	
	
	


	
	
	
}
